package service
////
import (
	"context"
	"{{.table.ModuleName}}/internal/model"
	"{{.table.ModuleName}}/internal/model/entity"
	"{{.table.ModuleName}}/internal/service/internal/dao"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"reflect"
)
////
type (
	s{{.table.ClassName}} struct{}
)
////
var (
	ins{{.table.ClassName}} = s{{.table.ClassName}}{}
)
////
func {{.table.ClassName}}() *s{{.table.ClassName}} {
	return &ins{{.table.ClassName}}
}
////
func (s *s{{.table.ClassName}}) PageList(ctx context.Context, param model.{{.table.ClassName}}) (total int, result []*entity.{{.table.ClassName}}, err error) {
    result = make([]*entity.{{.table.ClassName}}, 0)
	daoModel := dao.{{.table.ClassName}}.Ctx(ctx)
	daoModel = s.getWhereParam(daoModel, param)
	total, err = daoModel.Count()
	if err != nil {
		g.Log().Error(ctx, err)
		err = gerror.New("获取总行数失败")
		return
	}
	if total == 0 {
		return
	}
	err = daoModel.Page(param.PageNum, param.PageSize).Scan(&result)
	if err != nil {
		g.Log().Error(ctx, err)
		err = gerror.New("获取数据失败")
	}
	return
}
////
func (s *s{{.table.ClassName}}) List(ctx context.Context, param model.{{.table.ClassName}}) (result []*entity.{{.table.ClassName}}, err error) {
    result = make([]*entity.{{.table.ClassName}}, 0)
	daoModel := dao.{{.table.ClassName}}.Ctx(ctx)
	daoModel = s.getWhereParam(daoModel, param)
	err = daoModel.Scan(&result)
	if err != nil {
		g.Log().Error(ctx, err)
		err = gerror.New("获取数据失败")
	}
	return
}
////
func (s *s{{.table.ClassName}}) getWhereParam(daoModel *gdb.Model, param model.{{.table.ClassName}}) *gdb.Model {
    columns := dao.{{.table.ClassName}}.Columns()
	if !reflect.DeepEqual(param, model.{{.table.ClassName}}{}) {
{{range $index, $column := .table.Columns}}
    {{if eq $column.IsQuery "1"}}
         {{if and (eq $column.QueryType "EQ") (eq $column.GoType "string")}}
          if param.{{$column.GoField}} != "" {
            daoModel = daoModel.Where(columns.{{$column.GoField}},param.{{$column.GoField}})
          }
         {{end}}
    {{end}}
{{end}}
	}
	return daoModel
}
////
func (s *s{{.table.ClassName}}) Add(ctx context.Context, in model.{{.table.ClassName}}) (err error) {
	_, err = dao.{{.table.ClassName}}.Ctx(ctx).Save(in)
	return
}
////
func (s *s{{.table.ClassName}}) Edit(ctx context.Context, in model.{{.table.ClassName}}) (err error) {
	_, err = dao.{{.table.ClassName}}.Ctx(ctx).Where(dao.{{.table.ClassName}}.Columns().Id, in.Id).Update(in)
	return
}
////
func (s *s{{.table.ClassName}}) Delete(ctx context.Context, ids []int) (err error) {
	_, err = dao.{{.table.ClassName}}.Ctx(ctx).Delete(dao.{{.table.ClassName}}.Columns().Id, ids)
	if err != nil {
		return err
	}
	return
}


